import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '../router';
import { baseURL, ip } from '../config/baseURL';

// 创建axios实例
const service = axios.create({
  baseURL: ip,
  timeout: 10000
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 获取token并去除可能的空格
    const auth = localStorage.getItem('auth');
    console.log("登录获取的auth:",auth)
    if (auth) {
      // 确保token没有空格
      const trimmedToken = auth.trim();
      config.headers['auth'] = trimmedToken;
    }
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      // 处理响应错误
      if (error.response.status === 401) {
        ElMessage.error('授权已过期，请重新登录');
        // 清除用户信息
        localStorage.removeItem('token');
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('username');
        localStorage.removeItem('userRole');
        // 跳转到登录页
        router.push('/login');
      } else {
        ElMessage.error(error.response.data.message || '请求失败');
      }
    } else {
      ElMessage.error('网络错误，请检查您的网络连接');
    }
    return Promise.reject(error);
  }
);

export default service;
